package com.example.coolweather.android.util;


import android.text.TextUtils;

import com.example.coolweather.android.db.City;
import com.example.coolweather.android.db.County;
import com.example.coolweather.android.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Utility {
//解析网络返回的json数据，并存入对应的数据库

    //response 省份JSON字符串
    //true 解析成功，并写入表中，否则失败
    public static boolean handleProvinceResponse(String response){
        if(!TextUtils.isEmpty(response)){
            try {//ctrl+alt+t
                JSONArray jsonArray = new JSONArray(response);
                for (int i =0; i <jsonArray.length();i++){
                    //解析数据封装到Province对象中
                    JSONObject o =jsonArray.getJSONObject(i);
                    Province province = new Province();
                    province.setProvinceName(o.getString("name"));
                    province.setProvinceCode(o.getInt("id"));
                    province.save();//存入数据表
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        return false;
    }

    public static boolean handleCityResponse(String response,int provinceId){
        if (!TextUtils.isEmpty(response)){
            try {
                JSONArray allCities = new JSONArray(response);
                for (int i =0; i <allCities.length();i++){
                    //解析数据封装到Province对象中
                    JSONObject cityObject =allCities.getJSONObject(i);
                    City city = new City();
                    city.setProvinceId(provinceId);
                    city.setCityName(cityObject.getString("name"));
                    city.setCityCode(cityObject.getInt("id"));
                    city.save();//存入数据表
                }
                return true;
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return false;
    }


    public static boolean handleCountyResponse(String response,int cityId){
        if (!TextUtils.isEmpty(response)){
            try {
                JSONArray allCounties = new JSONArray(response);
                for (int i = 0;i< allCounties.length();i++){
                    JSONObject countyObject = allCounties.getJSONObject(i);
                    County county = new County();
                    county.setCountyName(countyObject.getString("name"));
                    county.setWeatherId(countyObject.getString("weather_id"));
                    county.setCityId(cityId);
                    county.save();


                }
                return true;
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return false;
    }



}
